// pages/main/main.js
const app = getApp()
const G = app.globalData
Page({

	/**
	 * 页面的初始数据
	 */
	data: {
		netgates: [],				// 所有网关
		netgate: 0,					// 当前网关id
		sensor_data: [],			// 各传感器的值
		switchs: [],				// 开关组
		switchs_changeing: false,  // 防抖，当一个开关正在启闭时为真，为真时多次点击无效。
	},
	
	changenetgate: function(e){
		console.log(e)
		this.setData({ 
			netgate: e.detail.current
		})
	},
	
	changeswitch: function(e){
		let that = this
		this.setData({
			switchs_changeing: true
		})
		// console.log(e)
		let id = e.currentTarget.dataset.id
		let switchname = e.currentTarget.dataset.name
		
		let status = e.detail.value ? 1 : 0 // 将status由ture/false转为1/0
		
		// console.log('id=', id, 'value=', value)
		app.get(app.urls.changetswitchstatus, {token: G.detail.token, id, status}, res => {
			console.log(res)
			wx.showToast({
				title: switchname + (res.data.status ? '已成功开启' : '已成功关闭'),
				icon: 'none'
			})
			that.setData({
				switchs_changeing: false
			})
		})
	},
	
	setting: function(){
		// 跳转到设置页
		wx.navigateTo({
			url: '/pages/setting/setting?netgate=' + this.data.netgate
		})
	},

	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad: function (options) {
		let that = this
		// this.storageLogin()
		console.log("now token is ", G.detail.token)
		app.get(app.urls.queryusergates, {token: G.detail.token}, res => {
			console.log("queryusergates => ", res)
			
			that.setData({
				netgates: res.data.netgates
			})
			let id = that.data.netgates[that.data.netgate].id  // 当前网关的id
			// 先读取当前网关下的开关组，把开关组先显示出来
			app.get(app.urls.queryuserswitchs, {token: G.detail.token, id: id}, res => {
				console.log("queryuserswitchs => ", res)
				
				that.setData({
					switchs: res.data.switch
				})
			}) 
			// 再更新当前网关下的各传感器的值
			app.get(app.urls.querylastdevicedata, {token: G.detail.token, id: id}, res => {
				console.log("querylastdevicedata => ", res.data.data[0].sensor_data)
				let sensor_data = res.data.data[0].sensor_data
				let sort = ['tempture', 'humidity', 'earthTemp', 'earthHum', 'solar']
				let high = ['low', 'mid', 'high']
				let arr = []
				for(let i in sort){
					let x = sensor_data[sort[i]]
					x.high = high[x.level]
					arr.push(x)
				}
				that.setData({
					sensor_data: arr
				})
			}) 
			
		})
	},

	/**
	 * 生命周期函数--监听页面初次渲染完成
	 */
	onReady: function () {

	},

	/**
	 * 生命周期函数--监听页面显示
	 */
	onShow: function () {

	},

	/**
	 * 生命周期函数--监听页面隐藏
	 */
	onHide: function () {

	},

	/**
	 * 生命周期函数--监听页面卸载
	 */
	onUnload: function () {

	},

	/**
	 * 页面相关事件处理函数--监听用户下拉动作
	 */
	onPullDownRefresh: function () {

	},

	/**
	 * 页面上拉触底事件的处理函数
	 */
	onReachBottom: function () {

	},

	/**
	 * 用户点击右上角分享
	 */
	onShareAppMessage: function () {

	},
	
	/*
	
	
	
	
	
	*/
})